from django import template

from util import parse_args_kwargs_and_as_var
from queryutils import executor

register = template.Library()

@register.tag(name="query")
def do_query(parser, token):
    nodelist = parser.parse(('endquery',))
    args, kwargs, as_var = parse_args_kwargs_and_as_var(parser, token.split_contents()[1:])
    parser.delete_first_token()
    return QueryNode(args, kwargs, as_var, nodelist)

class QueryNode(template.Node):
    def __init__(self, args, kwargs, as_var, nodelist):
        self.nodelist = nodelist
        self.evalto = kwargs.get('eval_to', None)
        self.onsuccessjsfunc = kwargs.get('success_func', False)
        self.onfailurejsfunc = kwargs.get('failure_func', False)
        self.name = kwargs.get('name').token
        self.query = kwargs.get('query').var
        self.queryargs = template.Variable(kwargs.get('query_args', '-1'))
        self.source = kwargs.get('source', 'db')
        
    def render(self, context):
        script = ''
        jscallback = ''
        result = executor.get(self.source).execute({'query' : self.query, 'query_args': self.queryargs.resolve(context)}).fetchall()
        if (self.evalto.token == 'context'):
            context[self.name] = result
        elif (self.evalto.token == 'js'):
            script = script + 'if(!__query__) __query__={}; __query__["__' + self.name + '__"]' + ' = ' + repr(result) + '; '
            if (self.onsuccessjsfunc):
                jscallback = self.onsuccessjsfunc.token
                script = script + jscallback + ('.call(null, %s)' % repr(result)) + '; '
                script = '''<script type='text/javascript' language='javascript'>%s</script>''' % script
        elif (self.evalto.token == 'jsonp'):
            jscallback = template.Variable("callback").resolve(context)
            script = script + jscallback + ('(%s)' % repr(result)) + '; '
        
        output = ''
        if (len(script) > 0):
            output = script
        return output